﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using DataAccess;
using System.Speech.Synthesis;
using System.IO;
using System.Speech.Recognition;

namespace ClickRead
{
  public static class SystemHelper
  {
    public static void GenerateAudios(string filepath, Repository repository)
    {
      List<string> logLines = new List<string>();
      logLines.Add("ID\tWords");
      foreach (var spot in repository.db.Spots)
      {
        string id = string.Format("{0}_{1}_{2}", spot.BookID.ToString(), spot.PageID.ToString(), spot.SpotID.ToString());
        if (!File.Exists(filepath + id + ".wav"))
        {
          TextToSpeechFile(filepath + id + ".wav", spot.Words);
          logLines.Add(string.Format("{0}\t{1}", id, spot.Words));
        }
      }

      System.IO.File.WriteAllLines(filepath + "log.txt", logLines);
    }

    public static RecognitionResult SpeechToText(Stream audioStream)
    {
      SpeechRecognitionHelper helper = new SpeechRecognitionHelper();
      helper.SpeechToText(audioStream);
      return helper.Result;
    }

    public static void TextToSpeechFile(string file, string text)
    {
      SpeechSynthesizer ss = new SpeechSynthesizer();
      using (MemoryStream memoryStream = new MemoryStream())
      {
        ss.SetOutputToWaveStream(memoryStream);
        ss.Speak(text);
        byte[] byteArr = memoryStream.ToArray();
        FileStream fs = System.IO.File.Create(file);
        fs.Write(byteArr, 0, byteArr.Length);
        fs.Close();
      }
    }
  }
}